// map/reduce/flat/mapflat/sum
// isArray/shuffle
// 去重/falt/排序


Array.prototype.myMap = function(cb){
    let res = []
    for(let i =0; i< this.length; i++){
        res.push(cb.call(this, this[i], i, this))
    }
    return res;
}
console.log([1,2].myMap((item) => (item +1)))



Array.prototype.myReduce = function(cb, initval){
    let res;
    let index = 0;
    if(initval === undefined){
        res = this[index]
        index++
    } else {
        res = initval
    }

    for(let i = index; i< this.length; i++){
        res = cb.call(this, res, this[i], i)
    }
    return res;

}
console.log([1,2,3].myReduce((pre,cur) => (pre*1+cur* 1), 1))



Array.prototype.myFlat = function(dep){
    let res = [];
    for(let i = 0; i< this.length; i++){
        if(Array.isArray(this[i]) && dep >= 1){
            let arr = this[i].myFlat(dep - 1)
            res = res.concat(arr)
        } else {
            res.push(this[i])
        }
    }
    return res;
}
console.log([1,1,[2,2,[3,3]]].myFlat(1))


Array.prototype.mySum = function(){
    return this.reduce((pre, next) => pre + next, 0)
}
console.log([1,2,3].mySum())



Array.prototype.myShuffle = function(){
    return this.sort((a, b) => Math.random() - 0.5)
}
console.log([1,2,3,4].myShuffle())


Array.myIsArray = function(obj){
    return Object.prototype.toString.call(obj) === '[object Array]'
}
console.log(Array.myIsArray([]))




Array.myMapFlat = function(arr, fn){
    const mappedArrays = arr.map(fn)
    return mappedArrays.reduce((pre, next) => pre.concat(next), [])
}
 // 使用示例  
 const numbers = [1, 2, 3];  
 const doubledAndSplitted = Array.myMapFlat(numbers, x => [x * 2, x * 3]);  
 console.log(doubledAndSplitted); // 输出: [2, 3, 4, 6, 6, 9]
